"use client";

import { useState, useEffect, Suspense } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { CheckCircle2, Loader2, Copy, Check, Clock } from "lucide-react";
import QRModal from "@/components/qr-modal";
import { useLanguage } from "@/context/language-provider";

interface ExamInfo {
  考试日期: string;
  星期: string;
  时间: string;
  课程名称: string;
  课程英文名?: string;
  开课部门: string;
  考试类别: string;
  考试形式: string;
  总学时: string;
  年级: string;
  专业名称: string | string[];
  人数: string;
  校区: string;
  机考平台: string;
  备注: string;
  source: string;
}

function SubmitForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const examParam = searchParams.get("exam");
  
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);
  const [cooldown, setCooldown] = useState(0);
  const [examInfo, setExamInfo] = useState<ExamInfo | null>(null);
  const [examOptions, setExamOptions] = useState<string[]>([]);
  const [selectedExam, setSelectedExam] = useState(examParam || "");
  const [questionsText, setQuestionsText] = useState("");
  const [signature, setSignature] = useState("");
  const [shareUrl, setShareUrl] = useState("");
  const [copied, setCopied] = useState(false);
  const [qrModalOpen, setQrModalOpen] = useState(false);
  const { language, isInternational } = useLanguage();
  
  // 生成随机署名
  function generateRandomSignature() {
    return Math.random().toString(36).substring(2, 10).toUpperCase();
  }
  
  // 客户端渲染后设置随机签名
  useEffect(() => {
    setSignature(generateRandomSignature());
  }, []);
  
  // 加载考试选项和详情
  useEffect(() => {
    async function fetchExams() {
      setLoading(true);
      try {
        // 添加国际化参数
        const response = await fetch(`/api/exams${isInternational ? '?int=true' : ''}`);
        const data = await response.json();
        
        if (data.exams && Array.isArray(data.exams)) {
          // 获取所有不重复的考试，包含名称和日期信息
          const uniqueExamsMap = new Map();
          
          data.exams.forEach((exam: ExamInfo) => {
            if ((exam.课程名称 || exam.课程英文名) && exam.考试日期) {
              const key = `${exam.课程名称 || exam.课程英文名}-${exam.考试日期}`;
              uniqueExamsMap.set(key, {
                name: exam.课程名称 || exam.课程英文名,
                englishName: exam.课程英文名,
                date: exam.考试日期,
                time: exam.时间,
                rawExam: exam
              });
            }
          });
          
          // 转换为数组并按日期排序
          const uniqueExams = Array.from(uniqueExamsMap.values());
          const today = new Date();
          today.setDate(today.getDate() - 2); // 设置为当前日期的2天前
          
          // 计算与今天的日期差并排序
          uniqueExams.sort((a, b) => {
            // 检查日期格式是否符合标准（例如：2023/05/01 或 2023/5/1）
            const isValidDateA = /^\d{4}\/\d{1,2}\/\d{1,2}$/.test(a.date);
            const isValidDateB = /^\d{4}\/\d{1,2}\/\d{1,2}$/.test(b.date);
            
            // 如果a不是有效日期但b是，将a排在后面
            if (!isValidDateA && isValidDateB) return 1;
            // 如果b不是有效日期但a是，将b排在后面
            if (isValidDateA && !isValidDateB) return -1;
            // 如果都不是有效日期，按字符串排序
            if (!isValidDateA && !isValidDateB) return a.date.localeCompare(b.date);
            
            // 两者都是有效日期，计算与今天的时间差
            const dateA = new Date(a.date);
            const dateB = new Date(b.date);
            
            // 检查日期是否有效（防止Invalid Date）
            if (isNaN(dateA.getTime()) || isNaN(dateB.getTime())) {
              return a.date.localeCompare(b.date);
            }

            const now = today.getTime();
            const ONE_DAY_MS = 24 * 60 * 60 * 1000;
            const SEVEN_DAYS_MS = 7 * ONE_DAY_MS;
            
            // 判断日期是否在今天之后或近期（过去7天内）
            const isAfterTodayA = dateA.getTime() >= now;
            const isAfterTodayB = dateB.getTime() >= now;
            const isRecentPastA = !isAfterTodayA && (now - dateA.getTime() <= SEVEN_DAYS_MS);
            const isRecentPastB = !isAfterTodayB && (now - dateB.getTime() <= SEVEN_DAYS_MS);
            
            // 按优先级排序：未来的考试 > 最近7天的考试 > 更早的考试
            // 如果一个是未来考试，一个不是，优先显示未来的考试
            if (isAfterTodayA && !isAfterTodayB) return -1;
            if (!isAfterTodayA && isAfterTodayB) return 1;
            
            // 如果一个是最近7天内的考试，一个是更早的考试，优先显示最近7天的
            if (isRecentPastA && !isRecentPastB && !isAfterTodayB) return -1;
            if (!isRecentPastA && isRecentPastB && !isAfterTodayA) return 1;
            
            // 如果都在未来，按从近到远排序
            if (isAfterTodayA && isAfterTodayB) {
              return dateA.getTime() - dateB.getTime();
            }
            
            // 如果都在最近7天内，按从近到远排序
            if (isRecentPastA && isRecentPastB) {
              return dateB.getTime() - dateA.getTime();
            }
            
            // 如果都在过去且不在最近7天内，按从近到远排序
            return dateB.getTime() - dateA.getTime();
          });
          
          // 设置排序后的选项
          setExamOptions(uniqueExams.map(exam => {
            // 国际版优先显示英文名称
            const displayName = isInternational && exam.englishName ? 
              exam.englishName : exam.name;
            return `${displayName} (${exam.date} ${exam.time || ''})`;
          }));
          
          // 如果URL中有考试参数，则设置为选中项
          if (examParam) {
            // 提取不包含年级的考试名称（如果有）
            const examNameWithoutYear = examParam.split(' ').length > 1 && 
              /^\d{4}$/.test(examParam.split(' ')[0]) 
              ? examParam.split(' ').slice(1).join(' ') 
              : examParam;
            
            // 查找匹配的考试信息
            const matchingExam = data.exams.find(
              (exam: ExamInfo) => exam.课程名称 === examNameWithoutYear || 
                                 exam.课程名称 === examParam ||
                                 (isInternational && exam.课程英文名 === examParam)
            );
            
            if (matchingExam) {
              // 国际版优先显示英文名称
              const displayCourseName = isInternational && matchingExam.课程英文名 ? 
                matchingExam.课程英文名 : matchingExam.课程名称;
              
              const displayName = `${displayCourseName} (${matchingExam.考试日期} ${matchingExam.时间 || ''})`;
              setSelectedExam(displayName);
              
              setExamInfo(matchingExam);
            }
          }
        }
      } catch (error) {
        console.error("加载考试数据失败", error);
      } finally {
        setLoading(false);
      }
    }
    
    fetchExams();
  }, [examParam, isInternational]);
  
  // 处理冷却倒计时
  useEffect(() => {
    if (cooldown <= 0) return;
    
    const timer = setTimeout(() => {
      setCooldown(cooldown - 1);
      if (cooldown === 1) {
        setSuccess(false);
      }
    }, 1000);
    
    return () => clearTimeout(timer);
  }, [cooldown]);
  
  // 处理复制链接
  const handleCopyLink = () => {
    if (shareUrl) {
      navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };
  
  // 提交表单
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!selectedExam || !questionsText.trim()) {
      return;
    }
    
    setSubmitting(true);
    
    try {
      const response = await fetch("/api/memories", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          exam: examInfo?.年级 ? `${examInfo.年级} ${selectedExam.split(' (')[0]}` : selectedExam.split(' (')[0],
          examDate: examInfo?.考试日期 || "",
          grade: examInfo?.年级 || "",
          source: examInfo?.source || "未知来源",
          questions: questionsText,
          signature: signature || (language === "zh" ? "匿名用户" : "Anonymous"),
          international: isInternational
        }),
      });
      
      if (response.ok) {
        const data = await response.json();
        
        // 清空表单
        setQuestionsText("");
        setSignature(generateRandomSignature());
        
        // 设置成功状态和冷却计时
        setSuccess(true);
        setCooldown(30); // 30秒冷却时间
        
        // 构建分享链接
        const baseUrl = window.location.origin;
        const examName = examInfo?.年级 ? `${examInfo.年级} ${selectedExam.split(' (')[0]}` : selectedExam.split(' (')[0];
        const viewerUrl = new URL(`${baseUrl}/viewer`);
        viewerUrl.searchParams.append("exam", examName);
        if (examInfo?.考试日期) {
          viewerUrl.searchParams.append("examDate", examInfo.考试日期);
        }
        if (examInfo?.年级) {
          viewerUrl.searchParams.append("grade", examInfo.年级);
        }
        // 添加国际化参数
        if (isInternational) {
          viewerUrl.searchParams.append("int", "true");
        }
        
        setShareUrl(viewerUrl.toString());
      } else {
        const errorData = await response.json();
        console.error("提交失败", errorData);
      }
    } catch (error) {
      console.error("提交过程中出错", error);
    } finally {
      setSubmitting(false);
    }
  };
  
  // 处理考试选择改变
  const handleExamChange = async (examDisplayName: string) => {
    setSelectedExam(examDisplayName);
    
    // 从选项中提取考试名称
    const examName = examDisplayName.split(" (")[0];
    
    try {
      // 添加国际化参数
      const response = await fetch(`/api/exams${isInternational ? '?int=true' : ''}`);
      const data = await response.json();
      
      if (data.exams && Array.isArray(data.exams)) {
        // 查找匹配的考试信息
        const matchingExam = data.exams.find(
          (exam: ExamInfo) => exam.课程名称 === examName || 
                            (isInternational && exam.课程英文名 === examName)
        );
        
        if (matchingExam) {
          setExamInfo(matchingExam);
        } else {
          setExamInfo(null);
        }
      }
    } catch (error) {
      console.error("获取考试详情失败", error);
    }
  };
  
  // 处理打开二维码模态窗口
  const handleOpenQrModal = () => {
    if (!shareUrl) {
      const baseUrl = window.location.origin;
      const params = new URLSearchParams();
      
      if (selectedExam) {
        const examName = selectedExam.split(" (")[0];
        params.append("exam", examName);
      }
      
      if (examInfo) {
        if (examInfo.考试日期) params.append("examDate", examInfo.考试日期);
        if (examInfo.年级) params.append("grade", examInfo.年级);
      }
      
      // 添加国际化参数
      if (isInternational) {
        params.append("int", "true");
      }
      
      setShareUrl(`${baseUrl}/submit?${params.toString()}`);
    }
    
    setQrModalOpen(true);
  };

  return (
    <div className="space-y-8 md:space-y-12">
      <div className="space-y-3 md:space-y-4">
        <h1 className="text-2xl md:text-4xl font-bold tracking-tight text-gradient">
          {language === "zh" ? "提交考试回忆" : "Submit Exam Memory"}
        </h1>
        <p className="text-base md:text-lg max-w-2xl" style={{ color: 'hsl(var(--foreground) / 0.7)' }}>
          {language === "zh" ? 
            "分享你的考试回忆，帮助其他同学更好地准备" : 
            "Share your exam experience to help others prepare better"
          }
        </p>
      </div>
      
      {loading ? (
        <div className="glass-panel flex justify-center items-center p-8 md:p-12">
          <div className="flex flex-col items-center">
            <Loader2 className="h-8 w-8 md:h-10 md:w-10 animate-spin text-primary" />
            <span className="mt-3" style={{ color: 'hsl(var(--foreground) / 0.6)' }}>
              {language === "zh" ? "加载中..." : "Loading..."}
            </span>
          </div>
        </div>
      ) : success ? (
        <div className="glass-panel p-5 space-y-6">
          <div className="flex items-start md:items-center gap-4">
            <div className="flex-shrink-0">
              <CheckCircle2 className="h-12 w-12 text-green-500" />
            </div>
            <div className="space-y-2">
              <h2 className="text-xl md:text-2xl font-semibold">
                {language === "zh" ? "提交成功" : "Submission Successful"}
              </h2>
              <p className="text-sm md:text-base" style={{ color: 'hsl(var(--foreground) / 0.7)' }}>
                {language === "zh" ?
                  "感谢你的分享，你的回忆已经成功提交！" :
                  "Thank you for sharing, your memory has been successfully submitted!"
                }
              </p>
            </div>
          </div>
          
          <div className="border-t pt-5" style={{ borderColor: 'hsl(var(--border) / 0.4)' }}>
            <p className="mb-3 text-sm font-medium">
              {language === "zh" ? "现在你可以：" : "Now you can:"}
            </p>
            <div className="flex flex-col md:flex-row gap-3">
              <a 
                href={shareUrl}
                className="glass-panel flex-1 p-4 rounded-lg hover:shadow-md transition-all"
              >
                <h3 className="text-lg font-medium mb-2">
                  {language === "zh" ? "查看回忆" : "View Memory"}
                </h3>
                <p className="text-sm" style={{ color: 'hsl(var(--foreground) / 0.7)' }}>
                  {language === "zh" ?
                    "查看你和其他同学提交的回忆内容" :
                    "View your submission and memories from other students"
                  }
                </p>
              </a>
              <button 
                onClick={handleCopyLink}
                className="glass-panel flex-1 p-4 rounded-lg hover:shadow-md transition-all text-left"
              >
                <h3 className="text-lg font-medium mb-2 flex items-center">
                  {copied ? (
                    <><Check className="h-5 w-5 mr-1.5 text-green-500" /> {language === "zh" ? "已复制" : "Copied"}</>
                  ) : (
                    <><Copy className="h-5 w-5 mr-1.5 text-primary" /> {language === "zh" ? "复制链接" : "Copy Link"}</>
                  )}
                </h3>
                <p className="text-sm" style={{ color: 'hsl(var(--foreground) / 0.7)' }}>
                  {language === "zh" ?
                    "分享给其他同学以便他们查看和贡献" :
                    "Share with others so they can view and contribute"
                  }
                </p>
              </button>
              <button 
                onClick={handleOpenQrModal}
                className="glass-panel flex-1 p-4 rounded-lg hover:shadow-md transition-all text-left"
              >
                <h3 className="text-lg font-medium mb-2">
                  {language === "zh" ? "生成二维码" : "Generate QR Code"}
                </h3>
                <p className="text-sm" style={{ color: 'hsl(var(--foreground) / 0.7)' }}>
                  {language === "zh" ?
                    "创建可扫描的二维码分享给他人" :
                    "Create a scannable QR code to share with others"
                  }
                </p>
              </button>
            </div>
          </div>
          
          <div className="border-t pt-5 flex items-center justify-between" style={{ borderColor: 'hsl(var(--border) / 0.4)' }}>
            <div className="flex items-center gap-2 text-sm" style={{ color: 'hsl(var(--foreground) / 0.6)' }}>
              <Clock className="h-4 w-4" />
              <span>
                {language === "zh" ?
                  `${cooldown}秒后可再次提交` :
                  `Can submit again in ${cooldown} seconds`
                }
              </span>
            </div>
            <button 
              className="px-4 py-1.5 rounded-lg text-sm transition-colors"
              style={{ 
                backgroundColor: 'hsl(var(--primary) / 0.1)', 
                color: 'hsl(var(--primary))' 
              }}
              onClick={() => setSuccess(false)}
            >
              {language === "zh" ? "继续提交" : "Continue Submitting"}
            </button>
          </div>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-4 md:space-y-6">
          <div className="glass-panel p-5 space-y-5">
            <div className="space-y-4">
              <label className="block space-y-2">
                <span className="text-sm font-medium flex items-center gap-2">
                  {language === "zh" ? "选择考试" : "Select Exam"}
                  <span className="text-red-500">*</span>
                </span>
                <select
                  value={selectedExam}
                  onChange={(e) => handleExamChange(e.target.value)}
                  className="modern-input w-full py-2.5 px-4"
                  required
                >
                  <option value="">{language === "zh" ? "-- 请选择考试 --" : "-- Select an exam --"}</option>
                  {examOptions.map((option) => (
                    <option key={option} value={option}>
                      {option}
                    </option>
                  ))}
                </select>
              </label>
              
              <label className="block space-y-2">
                <span className="text-sm font-medium flex items-center gap-2">
                  {language === "zh" ? "考题回忆" : "Exam Memory"}
                  <span className="text-red-500">*</span>
                </span>
                <textarea
                  value={questionsText}
                  onChange={(e) => setQuestionsText(e.target.value)}
                  className="modern-input w-full min-h-[200px] md:min-h-[300px] p-4"
                  placeholder={language === "zh" ? 
                    "请详细描述你记忆中的考试题目，包括题型、分值、难度等信息..." : 
                    "Please describe in detail the exam questions you remember, including question types, scores, difficulty..."
                  }
                  required
                />
              </label>
              
              <label className="block space-y-2">
                <span className="text-sm font-medium">
                  {language === "zh" ? "署名 (选填)" : "Signature (Optional)"}
                </span>
                <input
                  type="text"
                  value={signature}
                  onChange={(e) => setSignature(e.target.value)}
                  className="modern-input w-full py-2.5 px-4"
                  placeholder={language === "zh" ? "署名（可使用昵称）" : "Signature (nickname allowed)"}
                  maxLength={20}
                />
              </label>
            </div>
          </div>
          
          {examInfo && (
            <div className="glass-panel h-fit">
              <div className="border-b p-5" style={{ borderColor: 'hsl(var(--border) / 0.4)' }}>
                <h3 className="flex items-center gap-2 font-medium">
                  {language === "zh" ? "考试信息" : "Exam Information"}
                </h3>
              </div>
              <div className="p-5 text-sm">
                {/* 提取所有要显示的键值对 */}
                {(() => {
                  const fieldsToShow = [
                    { 
                      key: language === "zh" ? '考试日期' : 'Exam Date', 
                      value: examInfo.考试日期 + (examInfo.星期 ? ' ' + examInfo.星期 : '') 
                    },
                    { 
                      key: language === "zh" ? '时间' : 'Time', 
                      value: examInfo.时间 
                    },
                    { 
                      key: language === "zh" ? '课程名称' : 'Course Name', 
                      value: isInternational && examInfo.课程英文名 ? examInfo.课程英文名 : examInfo.课程名称 
                    },
                    { 
                      key: language === "zh" ? '开课部门' : 'Department', 
                      value: examInfo.开课部门 
                    },
                    { 
                      key: language === "zh" ? '考试形式' : 'Exam Format', 
                      value: examInfo.考试形式 
                    },
                    { 
                      key: language === "zh" ? '年级' : 'Grade', 
                      value: examInfo.年级 
                    },
                    { 
                      key: language === "zh" ? '专业' : 'Major', 
                      value: examInfo.专业名称 
                    },
                    { 
                      key: language === "zh" ? '校区' : 'Campus', 
                      value: examInfo.校区 
                    }
                  ];
                  
                  // 过滤掉空值
                  const validFields = fieldsToShow.filter(f => f.value);
                  
                  // 计算每列的字段数量
                  const halfLength = Math.ceil(validFields.length / 2);
                  const leftColumn = validFields.slice(0, halfLength);
                  const rightColumn = validFields.slice(halfLength);
                  
                  return (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
                      <div className="space-y-2">
                        {leftColumn.map((field) => (
                          <div key={field.key} className="flex gap-2">
                            <span className="min-w-[80px] font-medium" style={{ color: 'hsl(var(--foreground) / 0.6)' }}>{field.key}:</span>
                            <span>{field.value}</span>
                          </div>
                        ))}
                      </div>
                      <div className="space-y-2">
                        {rightColumn.map((field) => (
                          <div key={field.key} className="flex gap-2">
                            <span className="min-w-[80px] font-medium" style={{ color: 'hsl(var(--foreground) / 0.6)' }}>{field.key}:</span>
                            <span>{field.value}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                })()}
              </div>
            </div>
          )}
          
          <div className="flex flex-col sm:flex-row items-center gap-4">
            <button
              type="submit"
              disabled={submitting || !selectedExam || !questionsText.trim()}
              className="modern-button w-full sm:w-auto min-w-[120px] md:min-w-[150px]"
              style={{
                opacity: submitting || !selectedExam || !questionsText.trim() ? 0.7 : 1,
              }}
            >
              {submitting ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  {language === "zh" ? "提交中..." : "Submitting..."}
                </>
              ) : (
                language === "zh" ? "提交回忆" : "Submit Memory"
              )}
            </button>
            
            <button
              type="button"
              onClick={handleOpenQrModal}
              className="px-4 py-2 rounded-lg text-sm border bg-secondary/20 hover:bg-secondary/30 transition-all w-full sm:w-auto"
              style={{ borderColor: 'hsl(var(--border) / 0.5)' }}
            >
              {language === "zh" ? "分享此页面" : "Share This Page"}
            </button>
          </div>
        </form>
      )}
      
      {/* QR码模态窗口 */}
      <QRModal 
        isOpen={qrModalOpen} 
        onClose={() => setQrModalOpen(false)} 
        url={shareUrl}
      />
    </div>
  );
}

function SubmitPageContent() {
  return (
    <Suspense fallback={
      <div className="glass-panel flex justify-center items-center p-8 md:p-12">
        <div className="flex flex-col items-center">
          <Loader2 className="h-8 w-8 md:h-10 md:w-10 animate-spin text-primary" />
          <span className="mt-3" style={{ color: 'hsl(var(--foreground) / 0.6)' }}>
            加载中...
          </span>
        </div>
      </div>
    }>
      {/* 使用 Suspense 包裹使用 useSearchParams 的组件 */}
      <Suspense fallback={null}>
        <SearchParamsHandler />
      </Suspense>
      <SubmitForm />
    </Suspense>
  );
}

// 创建一个包含 useSearchParams 的子组件
function SearchParamsHandler() {
  const { setLanguage } = useLanguage();
  const router = useRouter();
  const searchParams = useSearchParams();
  
  useEffect(() => {
    const intParam = searchParams.get("int");
    if (intParam === "true") {
      // 设置语言为英文
      setLanguage("en");
    }
  }, [router, searchParams, setLanguage]);
  
  return null;
}

export default function SubmitPage() {
  return <SubmitPageContent />;
} 